﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Administration.Catalog.recTariffhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.Catalog;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Administration.Catalog
{

    public class recTariffhandler : SIPO.Web.BaseHandler
    {

        private recTariffRepo recTariffDal = new recTariffRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;

                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                try
                {
                    recTariff CekTarif = new recTariff();
                    CekTarif = recTariffDal.GetBySubSubSectorId((int)jo["SubSubSectorID"], (short)jo["TransTypeID"], true);
                    if (jo["CorporateActionTypeID"].ToString().Trim() != "")
                        CekTarif = recTariffDal.GetBySubSubSectorIdForCorporateAction((int)jo["SubSubSectorID"], (short)jo["TransTypeID"], true, (int)jo["CorporateActionTypeID"]);
                    else if (jo["RegistrationEmisionTypeID"].ToString().Trim() != "")
                        CekTarif = recTariffDal.GetBySubSubSectorIdForRegistrationEmisi((int)jo["SubSubSectorID"], (short)jo["TransTypeID"], true, (int)jo["RegistrationEmisionTypeID"]);
                    DateTime? NewStartdate = jo["StartDate"].ToString().Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(jo["StartDate"].ToString(), Helper.Culture.Indonesian);
                    DateTime? OldStartDate = CekTarif.StartDate.ToString().Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(CekTarif.StartDate.ToString(), Helper.Culture.English);
                    if (OldStartDate >= NewStartdate)
                    {
                        helper.Message = "Tanggal tarif baru harus lebih besar dari tarif lama !";
                        helper.IsSuccess = false;

                    }
                    else
                    {
                        //update tanggal berakhir tarif lama
                        CekTarif.EndDate = NewStartdate.Value.AddDays(-1);
                        CekTarif.IsActive = false;
                        recTariffDal.Update(CekTarif);
                        //insert tariff baru
                        recTariff obj = new recTariff();
                        if (jo["SectorID"].ToString().Trim() != "")
                            obj.SectorID = (int)jo["SectorID"];
                        if (jo["SubSectorID"].ToString().Trim() != "")
                            obj.SubSectorID = (int)jo["SubSectorID"];
                        if (jo["SubSubSectorID"].ToString().Trim() != "")
                            obj.SubSubSectorID = (int)jo["SubSubSectorID"];
                        if (jo["TransTypeID"].ToString().Trim() != "")
                            obj.TransTypeID = (Int16)jo["TransTypeID"];
                        if (jo["Percentage"].ToString().Trim() != "")
                            obj.Percentage = decimal.Parse(jo["Percentage"].ToString());
                        if (jo["Value"].ToString().Trim() != "")
                            obj.Value = Helper.ToDecimal(jo["Value"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["MinValue"].ToString().Trim() != "")
                            obj.MinValue = Helper.ToDecimal(jo["MinValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["MaxValue"].ToString().Trim() != "")
                            obj.MaxValue = Helper.ToDecimal(jo["MaxValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["Kelipatan"].ToString().Trim() != "")
                            obj.Kelipatan = Helper.ToDecimal(jo["Kelipatan"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["ImpositionBaseID"].ToString().Trim() != "")
                            obj.ImpositionBaseID = (short)jo["ImpositionBaseID"];
                        if (jo["CorporateActionTypeID"].ToString().Trim() != "")
                            obj.CorporateActionTypeID = (int)jo["CorporateActionTypeID"];
                        if (jo["RegistrationEmisionTypeID"].ToString().Trim() != "")
                            obj.RegistrationEmisionTypeID = (Int16)jo["RegistrationEmisionTypeID"];

                        bool isActive = true; //baru harus true, karena akan mengupdate yang sebelumnya false
                        bool isFormula = jo["IsFormula"] == null ? false : ((string)jo["IsFormula"] == "1" ? true : false);

                        obj.IsActive = isActive;
                        obj.IsFormula = isFormula;

                        if (jo["StartDate"].ToString().Trim() != "")
                            obj.StartDate = DateTime.ParseExact(jo["StartDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));
                        if (jo["EndDate"].ToString().Trim() != "")
                            obj.EndDate = DateTime.ParseExact(jo["EndDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));

                        obj.CreatedDate = DateTime.Now;
                        obj.CreatedBy = base.UserLoggedIn;

                        recTariffDal.Save(obj);

                        helper.Message = "Data berhasil di simpan !";
                        helper.IsSuccess = true;
                    }
                }
                catch //jika tidak ditemukan tarif sebelumnya
                {
                    //insert tariff baru
                    recTariff obj = new recTariff();
                    if (jo["SectorID"].ToString().Trim() != "")
                        obj.SectorID = (int)jo["SectorID"];
                    if (jo["SubSectorID"].ToString().Trim() != "")
                        obj.SubSectorID = (int)jo["SubSectorID"];
                    if (jo["SubSubSectorID"].ToString().Trim() != "")
                        obj.SubSubSectorID = (int)jo["SubSubSectorID"];
                    if (jo["TransTypeID"].ToString().Trim() != "")
                        obj.TransTypeID = (Int16)jo["TransTypeID"];
                    if (jo["Percentage"].ToString().Trim() != "")
                        obj.Percentage = decimal.Parse(jo["Percentage"].ToString());
                    if (jo["Value"].ToString().Trim() != "")
                        obj.Value = Helper.ToDecimal(jo["Value"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["MinValue"].ToString().Trim() != "")
                        obj.MinValue = Helper.ToDecimal(jo["MinValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["MaxValue"].ToString().Trim() != "")
                        obj.MaxValue = Helper.ToDecimal(jo["MaxValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["Kelipatan"].ToString().Trim() != "")
                        obj.Kelipatan = Helper.ToDecimal(jo["Kelipatan"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["ImpositionBaseID"].ToString().Trim() != "")
                        obj.ImpositionBaseID = (short)jo["ImpositionBaseID"];
                    if (jo["CorporateActionTypeID"].ToString().Trim() != "")
                        obj.CorporateActionTypeID = (int)jo["CorporateActionTypeID"];
                    if (jo["RegistrationEmisionTypeID"].ToString().Trim() != "")
                        obj.RegistrationEmisionTypeID = (Int16)jo["RegistrationEmisionTypeID"];

                    bool isActive = true; //baru harus true, karena akan mengupdate yang sebelumnya false
                    bool isFormula = jo["IsFormula"] == null ? false : ((string)jo["IsFormula"] == "1" ? true : false);

                    obj.IsActive = isActive;
                    obj.IsFormula = isFormula;

                    if (jo["StartDate"].ToString().Trim() != "")
                        obj.StartDate = DateTime.ParseExact(jo["StartDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));
                    if (jo["EndDate"].ToString().Trim() != "")
                        obj.EndDate = DateTime.ParseExact(jo["EndDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));

                    obj.CreatedDate = DateTime.Now;
                    obj.CreatedBy = base.UserLoggedIn;

                    recTariffDal.Save(obj);

                    helper.Message = "Data berhasil di simpan !";
                    helper.IsSuccess = true;
                }

            }
            catch (Exception ex)
            {
                if (ex.ToString().Contains("UI_recTariff"))
                {
                    helper.IsSuccess = false;
                    helper.Message = "Tarif sudah ada !";
                }
                else
                {
                    helper.IsSuccess = false;
                    helper.Message = ex.Message;
                }
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recTariffhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                try
                {
                    recTariff CekTarif = new recTariff();
                    CekTarif = recTariffDal.GetBySubSubSectorId((int)jo["SubSubSectorID"], (short)jo["TransTypeID"], true);
                    if (jo["CorporateActionTypeID"].ToString().Trim() != "")
                        CekTarif = recTariffDal.GetBySubSubSectorIdForCorporateAction((int)jo["SubSubSectorID"], (short)jo["TransTypeID"], true, (int)jo["CorporateActionTypeID"]);
                    else if (jo["RegistrationEmisionTypeID"].ToString().Trim() != "")
                        CekTarif = recTariffDal.GetBySubSubSectorIdForRegistrationEmisi((int)jo["SubSubSectorID"], (short)jo["TransTypeID"], true, (int)jo["RegistrationEmisionTypeID"]);
                    DateTime? NewStartdate = jo["StartDate"].ToString().Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(jo["StartDate"].ToString(), Helper.Culture.Indonesian);
                    DateTime? OldStartDate = CekTarif.StartDate.ToString().Equals(string.Empty) ? (DateTime?)null : Helper.FormatDate(CekTarif.StartDate.ToString(), Helper.Culture.English);
                    if (OldStartDate >= NewStartdate)
                    {
                        helper.Message = "Tanggal tarif harus lebih besar dari tarif lama !";
                        helper.IsSuccess = false;

                    }
                    else
                    {
                        //update tanggal berakhir tarif lama
                        CekTarif.EndDate = NewStartdate.Value.AddDays(-1);
                        recTariffDal.Update(CekTarif);

                        recTariff obj = new recTariff();
                        obj.TariffID = (int)jo["TariffID"];
                        if (jo["SectorID"].ToString().Trim() != "")
                            obj.SectorID = (int)jo["SectorID"];
                        if (jo["SubSectorID"].ToString().Trim() != "")
                            obj.SubSectorID = (int)jo["SubSectorID"];
                        if (jo["SubSubSectorID"].ToString().Trim() != "")
                            obj.SubSubSectorID = (int)jo["SubSubSectorID"];
                        if (jo["TransTypeID"].ToString().Trim() != "")
                            obj.TransTypeID = (Int16)jo["TransTypeID"];
                        if (jo["Percentage"].ToString().Trim() != "")
                            obj.Percentage = decimal.Parse(jo["Percentage"].ToString());
                        if (jo["Value"].ToString().Trim() != "")
                            obj.Value = Helper.ToDecimal(jo["Value"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["MinValue"].ToString().Trim() != "")
                            obj.MinValue = Helper.ToDecimal(jo["MinValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["MaxValue"].ToString().Trim() != "")
                            obj.MaxValue = Helper.ToDecimal(jo["MaxValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["Kelipatan"].ToString().Trim() != "")
                            obj.Kelipatan = Helper.ToDecimal(jo["Kelipatan"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        if (jo["ImpositionBaseID"].ToString().Trim() != "")
                            obj.ImpositionBaseID = (short)jo["ImpositionBaseID"];
                        if (jo["CorporateActionTypeID"].ToString().Trim() != "")
                            obj.CorporateActionTypeID = (int)jo["CorporateActionTypeID"];
                        if (jo["RegistrationEmisionTypeID"].ToString().Trim() != "")
                            obj.RegistrationEmisionTypeID = (Int16)jo["RegistrationEmisionTypeID"];

                        bool isActive = jo["IsActive"] == null ? false : ((string)jo["IsActive"] == "1" ? true : false);
                        bool isFormula = jo["IsFormula"] == null ? false : ((string)jo["IsFormula"] == "1" ? true : false);

                        obj.IsActive = isActive;
                        obj.IsFormula = isFormula;

                        if (jo["StartDate"].ToString().Trim() != "")
                            obj.StartDate = DateTime.ParseExact(jo["StartDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));
                        if (jo["EndDate"].ToString().Trim() != "")
                            obj.EndDate = DateTime.ParseExact(jo["EndDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));

                        obj.UpdatedDate = DateTime.Now;
                        obj.UpdatedBy = base.UserLoggedIn;

                        recTariffDal.Update(obj);

                        helper.Message = "Data berhasil di ubah !";
                        helper.IsSuccess = true;
                    }
                }
                catch
                { //jika tidak ditemukan tarif sebelumnya
                    recTariff obj = new recTariff();
                    obj.TariffID = (int)jo["TariffID"];
                    if (jo["SectorID"].ToString().Trim() != "")
                        obj.SectorID = (int)jo["SectorID"];
                    if (jo["SubSectorID"].ToString().Trim() != "")
                        obj.SubSectorID = (int)jo["SubSectorID"];
                    if (jo["SubSubSectorID"].ToString().Trim() != "")
                        obj.SubSubSectorID = (int)jo["SubSubSectorID"];
                    if (jo["TransTypeID"].ToString().Trim() != "")
                        obj.TransTypeID = (Int16)jo["TransTypeID"];
                    if (jo["Percentage"].ToString().Trim() != "")
                        obj.Percentage = decimal.Parse(jo["Percentage"].ToString());
                    if (jo["Value"].ToString().Trim() != "")
                        obj.Value = Helper.ToDecimal(jo["Value"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["MinValue"].ToString().Trim() != "")
                        obj.MinValue = Helper.ToDecimal(jo["MinValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["MaxValue"].ToString().Trim() != "")
                        obj.MaxValue = Helper.ToDecimal(jo["MaxValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["Kelipatan"].ToString().Trim() != "")
                        obj.Kelipatan = Helper.ToDecimal(jo["Kelipatan"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    if (jo["ImpositionBaseID"].ToString().Trim() != "")
                        obj.ImpositionBaseID = (short)jo["ImpositionBaseID"];
                    if (jo["CorporateActionTypeID"].ToString().Trim() != "")
                        obj.CorporateActionTypeID = (int)jo["CorporateActionTypeID"];
                    if (jo["RegistrationEmisionTypeID"].ToString().Trim() != "")
                        obj.RegistrationEmisionTypeID = (Int16)jo["RegistrationEmisionTypeID"];

                    bool isActive = jo["IsActive"] == null ? false : ((string)jo["IsActive"] == "1" ? true : false);
                    bool isFormula = jo["IsFormula"] == null ? false : ((string)jo["IsFormula"] == "1" ? true : false);

                    obj.IsActive = isActive;
                    obj.IsFormula = isFormula;

                    if (jo["StartDate"].ToString().Trim() != "")
                        obj.StartDate = DateTime.ParseExact(jo["StartDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));
                    if (jo["EndDate"].ToString().Trim() != "")
                        obj.EndDate = DateTime.ParseExact(jo["EndDate"].ToString(), "dd/MM/yyyy", new System.Globalization.CultureInfo("id-ID"));

                    obj.UpdatedDate = DateTime.Now;
                    obj.UpdatedBy = base.UserLoggedIn;

                    recTariffDal.Update(obj);

                    helper.Message = "Data berhasil di ubah !";
                    helper.IsSuccess = true;
                }
            }
            catch (Exception ex)
            {
                if (ex.ToString().Contains("UI_recTariff"))
                {
                    helper.IsSuccess = false;
                    helper.Message = "Tarif sudah ada !";
                }
                else
                {
                    helper.IsSuccess = false;
                    helper.Message = ex.Message;
                }
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recTariffhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["TariffID"];
                helper.Message = "Data berhasil di hapus !";
                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    recTariff tariff = recTariffDal.GetById(int.Parse(id));
                    {
                        if (tariff.IsActive == true)
                        {
                            try
                            {
                                recTariff CekTarif = recTariffDal.GetBySubSubSectorId(tariff.SubSubSectorID, tariff.TransTypeID, false);
                                CekTarif.EndDate = null;
                                CekTarif.IsActive = true;
                                recTariffDal.Update(CekTarif);
                                int intID = Convert.ToInt32(id);
                                recTariffDal.Delete(intID);
                            }
                            catch // jika tidak ditemukan tarif sebelumnya
                            {
                                int intID = Convert.ToInt32(id);
                                recTariffDal.Delete(intID);
                            }

                        }
                        else
                        {
                            helper.Message = "Tariff lama tidak dapat dihapus, hapus dahulu tarif terbaru !";
                        }
                    }
                }
                helper.IsSuccess = true;

            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "recTariffhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recTariff.Fields.TariffID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recTariff> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recTariffDal.SelectScalar(SQL.Function.Aggregate.Count, recTariff.Fields.TariffID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recTariffDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recTariffhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

    }

}